package com.example.tnot.Teacher.CoursePart.CourseInternal.CourseDetailHome;

import static com.example.tnot.login.fragmentui.LoginFragment.BASE_URL;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.tnot.R;
import com.example.tnot.Teacher.BaseFragment.BaseBackFragment;
import com.example.tnot.Teacher.CoursePart.ItemBean.rv_ClassListItem;
import com.example.tnot.Teacher.CoursePart.CourseInternal.CourseDetailHome.Adapter.rvClassListAdapter;
import com.example.tnot.api.HttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class CourseDetailFragment extends BaseBackFragment {
    private rvClassListAdapter classListAdapter;
    private ArrayList<JSONObject> student_list;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    ImageView iv_back, iv_add;
    LinearLayout ll_live, ll_publish, ll_statistics, ll_infor, ll_studentList, ll_activity;
    TextView tv_CourseName;
    private String mParam1;
    private String mParam2;
    View view;
    RecyclerView class_recycler_view;
    PopupWindow popupWindow;
    List<rv_ClassListItem> ClassList;


    public CourseDetailFragment() {
    }

    public static CourseDetailFragment newInstance(String param1, String param2) {
        CourseDetailFragment fragment = new CourseDetailFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        // 初始化数据列表，避免空指针
        ClassList = new ArrayList<>();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 1. 先加载布局
        view = inflater.inflate(R.layout.course_detail_fragment, container, false);

        // 2. 优先初始化RecyclerView，确保不为null
        initRecyclerView();

        // 3. 初始化其他视图
        initViews();

        // 4. 加载数据
        InitData();

        // 5. 获取并设置传递的数据
        setupCourseData();

        return view;
    }

    // 专门用于初始化RecyclerView的方法
    private void initRecyclerView() {
        class_recycler_view = view.findViewById(R.id.class_recycler_view);
        if (class_recycler_view == null) {
            Log.e("RecyclerView Error", "class_recycler_view为null，请检查布局文件中的ID是否正确");
            return;
        }

        // 设置布局管理器
        class_recycler_view.setLayoutManager(new LinearLayoutManager(getActivity()));

        // 初始化适配器
        classListAdapter = new rvClassListAdapter(ClassList);
        class_recycler_view.setAdapter(classListAdapter);
    }

    // 初始化其他视图控件
    private void initViews() {
        iv_back = view.findViewById(R.id.back);
        iv_back.setOnClickListener(v -> handleBackPressed());

        ll_live = view.findViewById(R.id.ll_live);
        ll_live.setOnClickListener(v -> {
            NavController navController = Navigation.findNavController(v);
            navController.navigate(R.id.action_courseDetailFragment_to_liveFragment);
        });

        ll_publish = view.findViewById(R.id.ll_publish);
        ll_publish.setOnClickListener(v -> {
            NavController navController = Navigation.findNavController(v);
            navController.navigate(R.id.action_courseDetailFragment_to_publishHomeFragment);
        });

        ll_statistics = view.findViewById(R.id.ll_statistics);
        ll_statistics.setOnClickListener(v -> {
            NavController navController = Navigation.findNavController(v);
            navController.navigate(R.id.action_courseDetailFragment_to_statisticsFragment);
        });

        ll_infor = view.findViewById(R.id.ll_infor);
        ll_infor.setOnClickListener(v -> {
            NavController navController = Navigation.findNavController(v);
            navController.navigate(R.id.action_courseDetailFragment_to_inforHomeFragment);
        });

        ll_studentList = view.findViewById(R.id.ll_studentList);
        ll_studentList.setOnClickListener(v -> {
            Bundle bundle=new Bundle();
            String CourseTeacher = getArguments().getString("CourseTeacher");
            bundle.putString("student_list_json",student_list.toString());
            bundle.putString("CourseTeacher",CourseTeacher);

            NavController navController = Navigation.findNavController(v);
            navController.navigate(R.id.action_courseDetailFragment_to_studentListFragment,bundle);
        });

        iv_add = view.findViewById(R.id.iv_add);
        iv_add.setOnClickListener(v -> {
            NavController navController = Navigation.findNavController(v);
            navController.navigate(R.id.action_courseDetailFragment_to_addClassFragment);
        });

        ll_activity = view.findViewById(R.id.ll_activity);
        ll_activity.setOnClickListener(v -> showCustomPopupWindow());

        tv_CourseName = view.findViewById(R.id.tv_CourseName);
    }

    // 设置课程数据
    private void setupCourseData() {
        if (getArguments() != null) {
            String CourseName = getArguments().getString("CourseName");

            Log.d("coursename", CourseName != null ? CourseName : "未获取到课程名称");
            if (CourseName != null) {
                tv_CourseName.setText(CourseName);
            }
        }
    }

    // 显示活动周围的弹窗
    private void showCustomPopupWindow() {
        // 避免重复创建
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            return;
        }

        View popupView = LayoutInflater.from(getContext()).inflate(R.layout.pop_up_window_course_activity, null);

        PopupWindow popupWindow = new PopupWindow(
                popupView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true
        );

        //设置背景，点击空白位置弹窗消失
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindow.setOutsideTouchable(true);

        popupWindow.showAsDropDown(ll_activity,-100,-350);

        // 设置菜单项点击事件
        popupView.findViewById(R.id.ll_lock_in).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(view);
                navController.navigate(R.id.action_courseDetailFragment_to_clockInHomeFragment);
                popupWindow.dismiss();
            }
        });
        popupView.findViewById(R.id.ll_QuickAnswer).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(view);
                navController.navigate(R.id.action_courseDetailFragment_to_quickAnswerHomeFragment);
                popupWindow.dismiss();
            }
        });

        popupView.findViewById(R.id.ll_roll_call).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(view);
                navController.navigate(R.id.action_courseDetailFragment_to_rollCallHomeFragment);
                popupWindow.dismiss();
            }
        });

        popupView.findViewById(R.id.ll_discuss).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NavController navController = Navigation.findNavController(view);
                navController.navigate(R.id.action_courseDetailFragment_to_disscussHomeFragment);
                popupWindow.dismiss();
            }
        });

    }
    private void InitData() {
        String URL = BASE_URL + "api/get_course_students";
        HashMap<String, String> params = new HashMap<>();
        String coures_id = getArguments() != null ? getArguments().getString("CourseId") : null;

        if (coures_id == null) {
            Log.e("InitData", "未获取到CourseId");
            // 添加测试数据
            ClassList.add(new rv_ClassListItem("测试班级", "10人", R.drawable.qr_code));
            fresh();
            return;
        }

        params.put("course_id", coures_id);
        String jsonData = HttpUtils.buildJsonString(params);

        HttpUtils.sendPostRequest(URL, jsonData, new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String response) throws JSONException {
                JSONArray jsonArray = new JSONArray(response);
                JSONArray datas = jsonArray.getJSONObject(2).getJSONArray("data");
                Log.d("课程信息", "网络请求成功，响应数据：" + datas);

                student_list= new ArrayList<JSONObject>();
                for(int i=0;i< datas.length();i++)
                {
                    student_list.add((JSONObject) datas.get(i));
                }

                // 清空现有数据
                ClassList.clear();

                // 从参数中获取班级列表
                if (getArguments() != null) {
                    String classData = getArguments().getString("ClassList");
                    JSONArray classList=new JSONArray(classData) ;
                    if (classList != null) {
                        for (int i=0;i<classList.length();i++) {
                            String className = classList.getJSONObject(i).getString("classname");
                            String count =classList.getJSONObject(i).getString("classnum");


                            ClassList.add(new rv_ClassListItem(className, count, R.drawable.qr_code));
                        }
                    } else {
                        Log.d("课程信息", "班级列表为空");
                        ClassList.add(new rv_ClassListItem("默认班级", String.valueOf(datas.length()), R.drawable.qr_code));
                    }
                }
                fresh();
            }

            @Override
            public void onFailure(String errorMsg) {
                Log.e("课程信息", "课程信息获取失败：" + errorMsg);
                // 清空现有数据
                ClassList.clear();
                // 网络失败时添加测试数据
                ClassList.add(new rv_ClassListItem("班级名称", "10人", R.drawable.qr_code));
                fresh();
            }
        });
    }

    // 刷新列表数据
    private void fresh() {
        if (getActivity() == null) return;

        getActivity().runOnUiThread(() -> {
            if (classListAdapter != null) {
                classListAdapter.notifyDataSetChanged();
            }
        });
    }
}
